package com.cxj.musicplayer.service;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;


import androidx.annotation.Nullable;

import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;

import com.cxj.musicplayer.activity.OnPlaying;
import com.cxj.musicplayer.bean.Song;
import com.cxj.musicplayer.data.ActivityManager;
import com.cxj.musicplayer.data.DataManager;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;


public class MediaService extends Service {
    private MediaPlayer mediaPlayer;
    public int currentPosition;
    private Timer timer;
    private String playState = "stop";
    private Song song;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public class MusicController {

        public String getPlayState(){
            return playState;
        }

        public void play(final OnPlaying onPlaying, final String song_id, int i, String source) throws IOException {
            String path = getApplicationContext().getFilesDir().getAbsolutePath();
            playState = "playing";
            if(timer != null){
                timer.cancel();
                timer.purge();
            }


            if(mediaPlayer != null){
                mediaPlayer.release();
                mediaPlayer = null;
            }

            try {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(path + "/songs/" + song_id + ".mp3");
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置音频类型
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }


            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    mp.seekTo(0);
                    Message message = new Message();
                    message.what = onPlaying.UPDATE_ALL_TIME;
                    Bundle bundle = new Bundle();
                    bundle.putString("all_time", millToTime(mediaPlayer.getDuration()));
                    message.setData(bundle);
                    onPlaying.handle.sendMessage(message);
                    onPlaying.sb.setMax(mediaPlayer.getDuration());

                    Message setBtn = new Message();
                    setBtn.what = onPlaying.UPDATE_BTN_STATE;
                    Bundle play_state = new Bundle();
                    play_state.putString("playState", playState);
                    setBtn.setData(play_state);
                    onPlaying.handle.sendMessage(setBtn);

                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    playState = "stop";
                    mediaPlayer.release();
                    mediaPlayer = null;
                    timer.cancel();
                    timer.purge();
                    currentPosition = 0;
                    song = null;
                }
            });
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!onPlaying.isSeekBarChanging && "playing".equals(playState)){
                        onPlaying.sb.setProgress(mediaPlayer.getCurrentPosition());
                        Message message = new Message();
                        message.what = onPlaying.UPDATE_PASS_TIME;
                        Bundle bundle = new Bundle();
                        bundle.putString("pass_time", millToTime(getPosition()));
                        message.setData(bundle);
                        onPlaying.handle.sendMessage(message);
                    }
                }
            },0,50);
            song = new Song();
            song.setSong_id(song_id);
            song.setAuthor(DataManager.array_data.get(source + "author_name")[i]);

            song.setSong_name(DataManager.array_data.get(source + "song_name")[i]);
            song.setCur_pos(i);
            song.setSource(source);
        }

        public Song getSongInfo(){
            return song;
        }

        public void finish(){
            if(timer != null){
                timer.cancel();
                timer.purge();
            }
            if(mediaPlayer != null){
                mediaPlayer.release();
            }
            song = null;
            playState = "stop";
            currentPosition = 0;
        }


        public void pause(){
            mediaPlayer.pause();
            currentPosition = getPosition();
            playState = "pause";
            if(timer != null){
                timer.cancel();
                timer.purge();
            }
        }

        public void restart(final OnPlaying onPlaying){
            if(timer != null){
                timer.cancel();
                timer.purge();
            }

            onPlaying.sb.setProgress(mediaPlayer.getCurrentPosition());
            Message message4 = new Message();
            message4.what = onPlaying.UPDATE_PASS_TIME;
            Bundle bundle4 = new Bundle();
            bundle4.putString("pass_time", millToTime(getPosition()));
            message4.setData(bundle4);
            onPlaying.handle.sendMessage(message4);

            Message message = new Message();
            message.what = onPlaying.UPDATE_ALL_TIME;
            Bundle bundle = new Bundle();
            bundle.putString("all_time", millToTime(mediaPlayer.getDuration()));
            message.setData(bundle);
            onPlaying.handle.sendMessage(message);
            onPlaying.sb.setMax(mediaPlayer.getDuration());

            Message setBtn = new Message();
            setBtn.what = onPlaying.UPDATE_BTN_STATE;
            Bundle play_state = new Bundle();
            play_state.putString("playState", playState);
            setBtn.setData(play_state);
            onPlaying.handle.sendMessage(setBtn);

            if(!"playing".equals(playState))
                return;


            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!onPlaying.isSeekBarChanging && "playing".equals(playState)){
                        onPlaying.sb.setProgress(mediaPlayer.getCurrentPosition());
                        Message message = new Message();
                        message.what = onPlaying.UPDATE_PASS_TIME;
                        Bundle bundle = new Bundle();
                        bundle.putString("pass_time", millToTime(getPosition()));
                        message.setData(bundle);
                        onPlaying.handle.sendMessage(message);
                    }
                }
            },0,50);

        }

        public void replay(final OnPlaying onPlaying){
            setPosition(currentPosition);
            mediaPlayer.start();
            if(timer != null){
                timer.cancel();
                timer.purge();
            }
            playState = "playing";
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(!onPlaying.isSeekBarChanging && "playing".equals(playState)){
                        onPlaying.sb.setProgress(mediaPlayer.getCurrentPosition());
                        Message message = new Message();
                        message.what = onPlaying.UPDATE_PASS_TIME;
                        Bundle bundle = new Bundle();
                        bundle.putString("pass_time", millToTime(getPosition()));
                        message.setData(bundle);
                        onPlaying.handle.sendMessage(message);
                    }
                }
            },0,50);
        }

        public long getMusicDuration(){
            return mediaPlayer.getDuration();
        }

        public int getPosition(){
            return mediaPlayer.getCurrentPosition();
        }

        public void setPosition(int position){
            mediaPlayer.seekTo(position);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        DataManager.concurrentHashMap_object_data.put("music_controller", new MusicController());
    }


    @Override
    public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        mediaPlayer.release();
        mediaPlayer = null;
        super.onDestroy();
    }

    public String millToTime(long mill){
        long m = mill / 60000;
        int s = (int) (mill % 60000 / 1000);
        return String.valueOf(m) + ":" + String.valueOf(s);
    }
}
